<?php
namespace Home\Controller;

use Think\Controller;

/**
 * 用户管理
 * @author DONGGUIYU
 *
 */
class UserController extends Controller
{
    /**
     * 用户列表
     */
    public function userList(){
    	// 用户名称
    	$username = I('post.username', "", 'htmlspecialchars');
    	// 手机号码
    	$phone = I('post.phone', "", 'htmlspecialchars');
    	if(!empty($username)){
    		$where['username'] = array('like', "%$username%");
    		$this->assign("username", $username);
    	}
    	if(!empty($phone)){
    		$where['phone'] = array('like', "%$phone%");
    		$this->assign("phone", $phone);
    	}
    	// 用户
    	$userModel = D('User');
    	// 分页
    	$page = setPage($userModel, $where);
    	// 进行分页数据查询
    	$orderby['id']='asc';
    	// 入口城市
    	if(isset($where)){
    	    $userList = $userModel->where($where)->order($orderby)->limit($page->firstRow.','.$page->listRows)->select();
    	} else {
    	    $userList = $userModel->order($orderby)->limit($page->firstRow.','.$page->listRows)->select();
    	}
    	$show = $page->show();// 分页显示输出
    	$this->assign('page',$show);// 赋值分页输出
    	$this->assign('userList', $userList);
        $this->display('userinfo');
    }
    
    /**
     * 添加用户
     */
    public function addUser(){
    	$this->assign('title','添加用户');
    	$this->display('edituser');
    }
    
    /**
     * 编辑用户
     */
    public function editUser(){
    	$this->assign('title','修改用户个人信息');
    	$userModel = D('User');
    	$userid = I('get.id', '', 'htmlspecialchars');
    	$where['id'] = $userid;
    	$user = $userModel->where($where)->select();
    	$this->assign('user', $user[0]);
    	$this->display('edituser');
    }
    
    /**
     * 用户是否已经存在
     */
    public function hasUser(){
        $id = I('post.id', '', 'htmlspecialchars');
        // 手机号码
        $phone = I('post.phone', '', 'htmlspecialchars');
        // 会员名(会员编号)
        $user_code = I('post.user_code', '', 'htmlspecialchars');
        // 昵称
        $username = I('post.username', '', 'htmlspecialchars');
        // 邮箱
        $email = I('post.email', '', 'htmlspecialchars');
        
        if(!empty($phone)){
            $params['phone'] = $phone;
            $message = "您输入的手机号";
        }
        
        if(!empty($user_code)){
            $params['user_code'] = $user_code;
            $message = "您输入的会员名";
        }
        
        if(!empty($username)){
            $params['username'] = $username;
            $message = "您输入的昵称";
        }
        
        if(!empty($email)){
            $params['email'] = $email;
            $message = "您输入的邮箱";
        }
        
        if(!empty($id)){
            $where['id'] = $id;
            $userModel = D('User');
            $rlt = $userModel->where($where)->select();
            if($rlt[0]['phone'] == $phone){
                unset($params['phone']);
            }
            if($rlt[0]['username'] == $username){
                unset($params['username']);
            }
            if($rlt[0]['user_code'] == $user_code){
                unset($params['user_code']);
            }
            if($rlt[0]['email'] == $email){
                unset($params['email']);
            }
            if(empty($params)){
                echo json_encode(array("status"=>500,"message"=>"不存在"));
            } else {
                if($this->checkHasExisted($params) == true){
                    echo json_encode(array("status"=>200,"message"=>$message."已经存在"));
                } else {
                    echo json_encode(array("status"=>500,"message"=>"不存在"));
                }
            }
            
        } else {
            if($this->checkHasExisted($params) == true){
                echo json_encode(array("status"=>200,"message"=>$message."已经存在"));
            } else {
                echo json_encode(array("status"=>500,"message"=>"不存在"));
            }
        }
    }
    
    /**
     * 保存用户
     */
    public function saveUser(){
    	$userModel = D('User');
    	$userid = I('post.userid', '', 'htmlspecialchars');
    	
    	// 会员名
    	$user_code = I('post.user_code','','htmlspecialchars');
    	// 昵称
    	$username = I('post.username', '', 'htmlspecialchars');
    	// 真实姓名
    	$realname = I('post.realname', '', 'htmlspecialchars');
    	// 性别
    	$sex = I('post.sex', '', 'htmlspecialchars');
    	// 手机号码
    	$phone = I('post.phone', '', 'htmlspecialchars');
    	// 电子邮箱
    	$email = I('post.email', '', 'htmlspecialchars');
    	
    	$data['user_code'] = $user_code;
    	$data['real_name'] = $realname;
    	$data['username'] = $username;
    	$data['sex'] = $sex;
    	$data['phone'] = $phone;
    	$data['email'] = $email;
    	
    	$rootPath = './Public/Resources/Images/HeadSculpture/';
    	// 文件上传
    	$config = array(
    			'maxSize'    =>    3145728,
    			'rootPath'   =>    $rootPath,
    			'savePath'   =>    '',
    			'saveName'   =>    '',
    			'exts'       =>    array('jpg', 'gif', 'png', 'jpeg'),
    			'autoSub'    =>    true,
    			'subName'    =>    "/".$username,
    			'replace'    =>    true,
    	);
    	$upload = new \Think\Upload($config);// 实例化上传类
    	
    	if(!empty($_FILES["file"]["name"])){
    		// 上传文件
    		$info   =   $upload->upload();
    		if(!$info) {// 上传错误提示错误信息
    			$this->error($upload->getError());
    		}else{
    			// 上传成功 获取上传文件信息
    			$data['head_sculpture'] =$info["file"]['savepath'].$info["file"]['savename'];
    		}
    	}
    	if(intval($userid) > 0){
    		$where['id'] = $userid;
    		$rlt = $userModel->where($where)->save($data);
    		if($rlt != 0 && $rlt == false){
    			$this->error('个人信息修改失败！');
    		} else {
    			$this->success('个人信息修改成功', 'userList');
    		}
    	} else {
    		$rlt = $userModel->data($data)->add();
    		if($rlt != 0 && $rlt == false){
    			$this->error('添加用户失败！');
    		} else {
    			$this->success('添加用户成功', 'userList');
    		}
    	}
    	
    }
    
    /**
     * 删除用户
     */
    public function deleteUser(){
    	$idList = I('post.idList', "", 'htmlspecialchars');
    	// 用户model
    	$userModel = D('User');
    	if(!empty($idList)){
    		$idArray = split(',', $idList);
    		// 开启事务
    		$userModel->startTrans();
    		foreach ($idArray as $id){
    		    unset($where);
    			$where['id'] = $id;
    			$rlt = $userModel->where($where)->delete();
    			if($rlt == false){
    				// 删除失败时回滚事务
    				$userModel->rollback();
    				$this->error("删除失败！");
    				exit;
    			}
    			// 旅游攻略Model
    			$travelTipModel = D('TravelTip');
    			unset($where);
    			$where['user_id'] = $id;
    			$rlt = $travelTipModel->where($where)->delete();
    			if($rlt == false){
    			    // 删除失败时回滚事务
    			    $userModel->rollback();
    			    $this->error("删除失败！");
    			    exit;
    			}
    		}
    		// 提交事务
    		$userModel->commit();
    		$this->success("删除成功！", 'userList');
    	}
    }
    
    /**
     * check原密码
     */
    function checkOldPwd(){
        $userModel = D('User');
        $password = I('post.oldpassword', '', 'htmlspecialchars');
        $where['id'] = I('post.userid', "", 'htmlspecialchars');
        $rlt = $userModel->where($where)->select();
        if(isset($rlt)){
            if(md5($password) == $rlt[0]['password']){
                echo "true";
            } else {
                echo "false";
            }
        } else{
        	echo "not found";
        }
    }
    
    /**
     * 修改密码
     */
    function alterPwd(){
        $userModel = D('User');
        // 密码
        $password = I('post.password', '', 'htmlspecialchars');
    
        $data['password'] = md5($password);
        $where['id'] = I('post.userid', '', 'htmlspecialchars');
        $rlt = $userModel->where($where)->save($data);
        if($rlt != 0 && $rlt == false){
            $this->error('密码修改失败！');
        } else {
            $this->success('密码修改成功', 'userList');
        }
    }
    
    /**
     * 检查手机号,会员名,昵称等是否已经存在
     * @param $params key:DB中各个字段名。如：`phone`,`user_code`,`username`.value:DB中各个字段所对应的值。如13511111111，00000001，我哦我我
     * @return boolean
     */
    private function checkHasExisted($params = array()){
        $userModel = D('User');
        foreach ($params as $key=>$value){
            $where[$key] = $value;
        }
        $rlt = $userModel->where($where)->getField("id");
        if($rlt > 0){
            return true; // 已存在
        } else {
            return false;  // 不存在
        }
    }
}

?>